<?php

class DB
{

  /* an instance of a QueryBuilder */
  var $_qb;
  var $_pdox;

  /* holds a singleton instance of the DB class */
  public static $current;

  function __construct($pdox, $qb)
  {
    Log::profile(__FILE__, "DB instance created constructor", 1);
    $this->_qb = $qb;
    $this->_pdox = $pdox;
  }


  /* Get the singleton instance of this class. */
  public static function get($pdox = null)
  {
    if (!DB::$current)
      {	
	$pdox = $pdox ? $pdox : PDOx::get();

	$qb = new QueryBuilder();
	DB::$current = new DB($pdox, $qb);
	Schema::load();
      }
    return DB::$current;
  }

  /* Get the singleton instance of this class. */
  public static function close($db)
  {
    $db->_qb = null;
  }

  /* Get the singleton instance of this class. */
  public static function isolated()
  {
    $pdox = PDOx::get();
    $qb = new QueryBuilder();
    $db = new DB($pdox, $qb);
    Schema::load();
    return $db;
  }

  /* A static method to create a Entity instance. */
  public static function entity($name, $args = null, $pdox = null, $qb = null)
  {
    $c = DB::get_entity_class($name);
    Log::dbg("DB::entity($name, $args = null, $pdox = null, $qb = null) : $c");
    if ($c)
      {
	$e = new $c($args, $pdox, $qb);	
      }
    else
      {
	Log::dbg("Entity $c does not exists, use Entity class.");
	$e = new Entity($name, $args, $pdox, $qb);
      }
    return $e;
  }

  /* A static method to create a Entity instance. */
  public static function entity_from_array($name, $data)
  {
    $c = DB::get_entity_class($name);
    Log::dbg("DB::entity_from_array($name, $data) : $c");
    if ($c)
      {
	$e = new $c();
      }
    else
      {
	Log::dbg("Entity $c does not exists, use Entity class.");
	$e = new Entity($name);
      }
    $e->feed($data);
    $e->_count = 1;
    return $e;
  }

  /* A static method to create a Entity instance. */
  public static function entity_abstract($name)
  {
    $c = DB::get_entity_class($name);
    Log::dbg("DB::entity_abstract($name) : $c");
    if ($c)
      {
	$e = new $c($name);
      }
    else
      {
	Log::dbg("Entity $c does not exists, use Entity class.");
	$e = new Entity($name);
      }
    return $e;
  }

  public static function get_entity_class($name)
  {

    $c = $name;
    if (class_exists($c))
      {
	return $c;
      }

    $c = $GLOBALS["PEA_CLASS_PREFIX"]. "$name";
    if (class_exists($c))
      {
	return $c;
      }

    return null;
  }

  function __get($name)
  {
    return DB::entity($name, null, $this->_pdox, $this->_qb);
  }

  public function __call($name, $args) {
    return DB::entity($name, $args, $this->_pdox, $this->_qb);
  }

}

?>